package com.wjp.banquet.common.config;


import com.wjp.banquet.common.enums.ResponseEnum;
import com.wjp.banquet.common.exception.BusinessException;
import com.wjp.banquet.common.util.ExceptionUtil;
import com.wjp.banquet.common.util.MessageUtil;
import com.wjp.banquet.common.util.StringUtil;
import com.wjp.banquet.common.vo.CommonRsp;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;


/**
 * @Description 修复平台的全局异常处理只能获取 "系统内部错误"
 * @Author
 * @Date 2020/3/17 14:19   平台也有类似的 ExceptionHandler   不过它处理的时候，丢失了错误提示，都是统一的：系统内部错误！   这不便于排查问题
 */
@Slf4j
@ControllerAdvice
public class ExceptionHandle {


    /**
     * 判断错误是否是已定义的已知错误，不是则由未知错误代替，同时记录在log中
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = RuntimeException.class)
    @ResponseBody
    public CommonRsp<?> afterException(Exception e, HttpServletResponse response) {
        e.printStackTrace();
        response.setStatus(ResponseEnum.SUCCESS.getCode());
        String errorMsg = null;
        if(e instanceof BusinessException){
            BusinessException businessException = (BusinessException)e;
            errorMsg = businessException.getMsg();
        }
        if(StringUtil.isEmpty(errorMsg)){
            errorMsg = e.getMessage();
        }

        if(StringUtil.isEmpty(errorMsg)){
            errorMsg = ExceptionUtil.getStackTrace(e);
        }
        log.error(errorMsg);
        return MessageUtil.fail(ResponseEnum.FAIL.getCode(),errorMsg,null);
    }

}
